package com.xiaoyun.security.springmvc.service;

import com.xiaoyun.security.springmvc.model.AuthenticationRequest;
import com.xiaoyun.security.springmvc.model.UserDto;
import org.springframework.stereotype.Service;
import org.springframework.util.StreamUtils;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

@Service
public class AuthenticationServiceImpl implements AuthenticationService {


    private Map<String, UserDto> userMap = new HashMap<>();

    {
        Set<String> authorities1 = new HashSet<>();
        authorities1.add("p1");
        Set<String> authorities2 = new HashSet<>();
        authorities2.add("p2");
        userMap.put("zhangshan", new UserDto("1010", "zhangshan", "123", "张三", "123456", authorities1));
        userMap.put("lisi", new UserDto("1011", "lisi", "456", "李四", "654321", authorities2));
    }

    @Override
    public UserDto authentication(AuthenticationRequest authenticationRequest) {
        if (authenticationRequest == null ||
                StringUtils.isEmpty(authenticationRequest.getUsername()) ||
                StringUtils.isEmpty(authenticationRequest.getPassword())) {
            throw new RuntimeException("账号和密码为空");
        }
        //根据账号去查询数据库，
        UserDto user = getUserDto(authenticationRequest.getUsername());
        if (user == null) {
            throw new RuntimeException("查询不到该用户");
        }
        if (!authenticationRequest.getPassword().equals(user.getPassword())) {
            throw new RuntimeException("账号或者密码错误");
        }
        return user;
    }

    private UserDto getUserDto(String username) {
        return userMap.get(username);
    }
}
